package com.john.utils.common;

import com.john.utils.enums.CharsetName;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 文件流处理工具类
 */
public class StreamUtils {

	final static int BUFFER_SIZE = 4096;

	/**
	 * 将InputStream转换成某种字符编码的String
	 * @param in InputStream
	 * @param charsetName CharsetName
	 */
	public static String InputStreamToString(InputStream in, CharsetName charsetName) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[BUFFER_SIZE];
		String string = null;
		int count = 0;
		try {
			while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
				outStream.write(data, 0, count);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			string = new String(outStream.toByteArray(), charsetName.getName());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return string;
	}

	/**
	 * 将String转换成InputStream
	 * @param in String
	 * @param charsetName CharsetName
	 */
	public static InputStream StringToInputStream(String in, CharsetName charsetName) throws Exception {
		ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes(charsetName.getName()));
		return is;
	}

	/**
	 * 将InputStream转换成byte数组
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] InputStreamToByte(InputStream in) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[BUFFER_SIZE];
		int count = 0;
		while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
			outStream.write(data, 0, count);
		return outStream.toByteArray();
	}

	/**
	 * 将byte数组转换成InputStream
	 */
	public static InputStream byteTOInputStream(byte[] in){
		ByteArrayInputStream is = new ByteArrayInputStream(in);
		return is;
	}

	/**
	 * 将byte数组转换成String
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String byteTOString(byte[] in) {
		InputStream is = null;
		try {
			is = byteTOInputStream(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return InputStreamToString(is, CharsetName.CHAR_UTF_8);
	}

	/**
	 * 获取文件InputStream
	 * @param fileName
	 * @return
	 */
	public static InputStream getFileInputStream(String fileName){
		return StreamUtils.class.getClassLoader().getResourceAsStream(fileName);
	}



	/**
	 * 获取文件输入流处理
	 */
	public static FileInputStream getFileInputStream(File file) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			System.out.print("错误信息:文件不存在");
			e.printStackTrace();
		}
		return fileInputStream;
	}

	/**
	  * 获取文件输出流处理
	 * @param append true:文件以追加方式打开,false:则覆盖原文件的内容
	 */
	public static FileOutputStream getFileOutputStream(File file,boolean append) {
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(file,append);
		} catch (FileNotFoundException e) {
			System.out.print("错误信息:文件不存在");
			e.printStackTrace();
		}
		return fileOutputStream;
	}

	/**
	 * 读TXT文件内容
	 * @param
	 * @return
	 */
	public static String readTxtFile(File file){
		StringBuffer buffer  = new StringBuffer();
		try {
			String encoding="utf-8";
			if(file.isFile() && file.exists()){ //判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file),encoding);//考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while((lineTxt = bufferedReader.readLine()) != null){
					buffer.append(lineTxt);
				}
				read.close();
			}else{
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		System.out.println("读取文件内容为:"+buffer.toString());
		return buffer.toString();
	}

	/**
	 * 写入文件流
	 */
	public static void witrs(String str,String savefile){
		FileWriter writer;
		try {
			writer = new FileWriter(savefile);
			writer.write(str);
			writer.flush();
			writer.close();
			System.out.println("文件写入成功地址是:"+savefile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将InputStream写入本地文件
	 * @param destination 写入本地目录
	 * @param input    输入流
	 * @throws IOException
	 */
	public static void writeToLocal(String destination, InputStream input){
		try {
			System.out.println(destination);
			int index;
			byte[] bytes = new byte[1024];
			File file = new File(destination);
			if(file.exists()){
				file.createNewFile();
			}
			FileOutputStream downloadFile = new FileOutputStream(destination);
			while ((index = input.read(bytes)) != -1) {
				downloadFile.write(bytes, 0, index);
				downloadFile.flush();
			}
			downloadFile.close();
			input.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 将InputStream写入到OutputStream
	 * @param input
	 * @param output
	 */
	public static void writeStream(InputStream input, OutputStream output){
		try {
			ReadableByteChannel inputChannel = Channels.newChannel(input);
			WritableByteChannel outputChannel = Channels.newChannel(output);
			ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
			while (inputChannel.read(buffer) != -1) {
				buffer.flip();
				outputChannel.write(buffer);
				buffer.clear();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}